// 定义发注构造器 Point
function Point(x, y) {
    this.x = x;
    this.y = y;
}

// 根据勾股定理计算两点之间的距离
function Line(p1, p2) {
    this.p1 = p1;
    this.p2 = p2;
    this.length = Math.sqrt(
        Math.pow(p1.x - p2.x, 2) +
        Math.pow(p1.y - p2.y, 2)
    )
}

// Shape构造器
function Shape() {
    this.points = [];
    this.lines = [];
    this.init();
}

Shape.prototype = {
    constructor: Shape,
    init: function () {
        if (this.context === undefined) {
            let canvas = document.getElementById('canvas');
            Shape.prototype.context = canvas.getContext('2d');
        }
    },

    draw: function () {
        let i, ctx = this.context;
        ctx.strokeStyle = this.getColor();
        ctx.beginPath();
        ctx.moveTo(this.points[0].x, this.points[0].y);
        for (i = 1; i < this.points.length; i++) {
            ctx.lineTo(this.points[i].x, this.points[i].y);
        }
        ctx.closePath();
        ctx.stroke();
    },

    getColor: function () {
        let i, rgb = [];
        for (i = 0; i < 3; i++) {
            rgb[i] = Math.round(255 * Math.random());
        }
        return 'rgb(' + rgb.join(',') + ')';
    },

    getLines: function () {
        if (this.lines.length > 0) {
            return this.lines;
        }
        let i, lines = [];
        for (i = 0; i < this.points.length; i++) {
            lines[i] = new Line(this.points[i], this.points[i + 1] || this.points[0]);
        }
        this.lines = lines;
        return lines;
    },

    getArea: function () {
    },

    getPerimeter: function () {
        let i, perim = 0, lines = this.getLines();
        for (i = 0; i < lines.length; i++) {
            perim += lines[i].length;
        }
        return perim;
    }
};

function Triangle(a, b, c) {
    this.points = [a, b, c];
    this.getArea = function () {
        let p = this.getPerimeter(),
            s = p / 2;
        return Math.sqrt(
            s
            * (s - this.lines[0].length)
            * (s - this.lines[1].length)
            * (s - this.lines[2].length)
        )
    }
}

function Rectangle(p, side_a, side_b) {
    this.points = [
        p,
        new Point(p.x + side_a, p.y),
        new Point(p.x + side_a, p.y + side_b),
        new Point(p.x, p.y + side_b),
    ];
    this.getArea = function () {
        return side_a * side_b;
    }
}

function Square(p, side) {
    Rectangle.call(this, p, side, side);
}

(function () {
    let s = new Shape();
    Triangle.prototype = s;
    Rectangle.prototype = s;
    Square.prototype = s;
})();

// 三角形绘制
let p1 = new Point(100, 100),
    p2 = new Point(300, 100),
    p3 = new Point(200, 0),
    t = new Triangle(p1, p2, p3);
t.draw();
t.getPerimeter();
t.getArea();

// 长方形绘制
let r = new Rectangle(new Point(200, 200), 50, 100);
r.draw();
r.getArea();
r.getPerimeter();

// 正方形绘制
let s = new Square(new Point(130, 130), 50);
s.draw();
s.getArea();
s.getPerimeter();

// 正方形绘制
new Square(p1, 200).draw();

















